from django import forms
from django.core.cache import cache

from apps.forms import FormMixin
from apps.ynauth.models import User


class LoginForm(forms.Form, FormMixin):
    email = forms.EmailField()
    password = forms.CharField(min_length=6, max_length=20, error_messages={
        "min_length": "长度不少于6个字符",
        "max_length": "长度不大于20个字符"
    })
    remember = forms.IntegerField(required=False)

class SignupForm(forms.Form, FormMixin):
    email = forms.EmailField(error_messages={
        'invalid': '请输入邮箱格式！',
        'required': '请输入邮箱！'
    })
    username = forms.CharField(max_length=20, min_length=2, error_messages={
        'max_length': '用户名最大长度不超过20位！',
        'min_length': '用户名最小长度不超过2位',
        'required': '请输入用户名！'
    })
    password = forms.CharField(max_length=16, min_length=6, error_messages={
        'max_length': '输入密码位数在6至16位！',
        'min_length': '输入密码位数在6至16位！',
        'required': '请输入密码！'
    })
    password_repeat = forms.CharField(max_length=16, min_length=6, error_messages={
        'max_length': '两次密码输入不一致！',
        'min_length': '两次密码输入不一致！'
    })
    img_captcha = forms.CharField(max_length=4, min_length=4, error_messages={
        'max_length': '图形验证码错误！',
        'min_length': '图形验证码错误！'
    })
    email_captcha = forms.CharField(max_length=4, min_length=4, error_messages={
        'max_length': '验证码错误！',
        'min_length': '验证码错误！'
    })

    def clean(self):
        cleaned_data = super(SignupForm, self).clean()
        password = cleaned_data.get('password')
        password_repeat = cleaned_data.get('password_repeat')
        if password != password_repeat:
            raise forms.ValidationError('两次密码输入不一致！')
        img_captcha = cleaned_data.get('img_captcha', 'none')
        if not cache.get(img_captcha.lower()):
            raise forms.ValidationError('图形验证码错误！')
        email = cleaned_data.get('email')
        email_captcha = cleaned_data.get('email_captcha')
        cache_email_captcha = cache.get(email)
        if not cache_email_captcha or cache_email_captcha.lower() != email_captcha.lower():
            raise forms.ValidationError('邮箱验证码错误！')
        exists = User.objects.filter(email=email).exists()
        if exists:
            raise forms.ValidationError('该邮箱已被注册！')